package com.sam.im.heiqun.uis.activities;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.sam.im.heiqun.R;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.FanYiBean;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.MsgEntity;
import com.sam.im.heiqun.entities.RedPacketHistoryEntivity;
import com.sam.im.heiqun.entities.beans.ImageInfoBean;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.ChatGroupRecyclerAdapter;
import com.sam.im.heiqun.uis.adapters.ChatRecyclerAdapter;
import com.sam.im.heiqun.uis.dialogs.MyAlertDialogManages;
import com.sam.im.heiqun.utils.IMMessageUtil;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.google.gson.Gson;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.StringUtils;
import com.yuyh.library.utils.data.safe.MD5;
import com.yuyh.library.utils.toast.ToastUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * 聊天历史记录
 * Created by wangguodong on 2017/1/11.
 */
public class ChatHistoryActivity extends BaseSwipeBackActivity implements  View.OnClickListener {
//public class ChatHistoryActivity extends Activity implements  View.OnClickListener {

    private static final String TAG = ChatHistoryActivity.class.getSimpleName();

    RecyclerView pullList;

    EditText search;

    private String redPackageId;

    private String uid;
    private String startMsgId;
    private List<ImMessage> datas;

    //    private PullToRefreshRecyclerView myList;
    private ChatRecyclerAdapter tbAdapter;
    private ChatGroupRecyclerAdapter groupAdapter;


    private int isGroup = 1;//判断是否是群组；1-是好友；2-是群组；
    private PGService mPGservice;
    private static final int RESULT_TRANSFER_GET = 103;
    private Dialog redDialog;

    @Override
    public int getContentViewId() {
        return R.layout.activity_chat_history;
    }

    @Override
    protected String getTitleText() {
        return getResources().getString(R.string.chat_history);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        initViewsm();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_chat_history);

    }

    protected void initViewsm() {
        mPGservice = PGService.getInstance();
//        TextView title = (TextView) findViewById(R.id.pre_tv_title);
//        title.setText(R.string.chat_history);
        ImageView backImg = (ImageView) findViewById(R.id.pre_v_back);
        backImg.setOnClickListener(this);
        getPassData();
        initNeedData();
        getMsgHistory();

    }

    /**
     * 初始化 需要用到的 值
     */
    private void initNeedData() {
        search = (EditText) findViewById(R.id.search);
        pullList = (RecyclerView) findViewById(R.id.content_lv);
        search.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER
                        && event.getAction() == KeyEvent.ACTION_DOWN) {
                    String trim = search.getText().toString().trim();
                    if (trim==null|| StringUtils.isEmpty(trim)){
                        ToolsUtils.showToast(ChatHistoryActivity.this,getResources().getString(R.string.search_content_null));
                    }else {
                        searchHistomsg(trim);
                    }
                    return true;
                }
                return false;
            }
        });
    }
    private void searchHistomsg(String s){
        int size = datas.size();
        for (int i = 0; i < size; i++) {
            ImMessage message = datas.get(i);
            Integer type = message.getMessageType();
            if (type == Constant.MESSAGE_TYPR_TEXT | type == Constant.MESSAGE_TYPR_BQEMOJI) {
                String content = message.getContent();
                try {
                    MsgEntity msgEntity = new Gson().fromJson(content, MsgEntity.class);
                    if (msgEntity.getMsgString().contains(s)) {
                        pullList.getLayoutManager().scrollToPosition(i);
                        return;
                    }

                } catch (Exception e) {
                    if (content.contains(s)) {
                        pullList.getLayoutManager().scrollToPosition(i);
                        return;
                    }
                }

            }
        }
        Toast.makeText(ChatHistoryActivity.this, R.string.none_find_chat_history, Toast.LENGTH_SHORT).show();
    }
    /**
     * 获取传递进来的值
     */
    private void getPassData() {
        Intent intent = getIntent();
        uid = intent.getStringExtra("uid");
        startMsgId = intent.getStringExtra("startMsgId");
        isGroup = intent.getIntExtra("isGroup", 1);
    }


    /**
     * 获取聊天记录
     */
    private void getMsgHistory() {
        datas = new ArrayList<>();
        pullList.setLayoutManager(new LinearLayoutManager(this));
        String myUserId = ToolsUtils.getMyUserId();
        if (isGroup == 1) {
            datas = ImMessage.find(ImMessage.class, "uniqueness=?", myUserId + "_" + uid);

            tbAdapter = new ChatRecyclerAdapter(this, datas, new ChatRecyclerAdapter.OnreadMsgListenler() {
                @Override
                public void sendread(List<String> msgids) {

                }
            }, new ChatRecyclerAdapter.OnlongclickMsgListenler() {
                @Override
                public void onOnTextMsgClicked(String text)
                {

                }

                @Override
                public void msgLongClick(int position, int type, View view) {

                    }
            });
            tbAdapter.setOnclickDownloadListenler(new ChatRecyclerAdapter.OnclickDownloadListenler() {
                @Override
                public void clickDown(int positon, int type) {

                }
            });
            pullList.setAdapter(tbAdapter);

            if (null!=datas && datas.size() > 0){
                ArrayList<ImageInfoBean> imagelist = new ArrayList<>();
                for (int i = 0; i < datas.size(); i++) {
                    if (datas.get(i).getType() == ChatRecyclerAdapter.TO_USER_IMG){
                        ImMessage tbub = datas.get(i);
                        String imageUrlSrc = "" ;
                        // Log.i("info","适配器接收到的内容=="+tbub.toString());
                        if (tbub.getFilePath() != null && !tbub.getFilePath().equals("")) {
                            imageUrlSrc = tbub.getFilePath();
                        } else if (tbub.getFileUrl() != null) {
                            imageUrlSrc = tbub.getFileUrl();
                        } else {
                            imageUrlSrc = tbub.getContent(); // 转发图片链接从这里取
                        }
                        imagelist.add(new ImageInfoBean(imageUrlSrc, IMMessageUtil.canImageForward(tbub)));
                    }
                }
                tbAdapter.setImageList(imagelist);
            }


            tbAdapter.setRedPacketListener(new ChatRecyclerAdapter.RedPacketOnClick() {

                @Override
                public void redOnClick(ImMessage imMessage, int type) {
                    String content = imMessage.getContent();
                    Bundle bundle = new Bundle();
                    redPackageId = ToolsUtils.getRedPacketInfo(content);
                    switch (type) {//0-获取；1-发送
                        case 0://
                            if (!ToolsUtils.currentNetState(ChatHistoryActivity.this)) {//当前网络不可用
                                break;
                            }
                            getRedPacketHistory(redPackageId);
                            break;
                        case 1:
                            showProgress(getResources().getString(R.string.now_open));
                            mPGservice.getRedPacketHistory(redPackageId, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<RedPacketHistoryEntivity>() {
                                @Override
                                protected void onResultError(ApiException ex) {
                                    hideProgress();
                                    showToast(getResources().getString(R.string.net_error));
                                }

                                @Override
                                public void onNext(RedPacketHistoryEntivity redPacketHistoryEntivity) {
                                    hideProgress();
                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable("redPacketId", redPacketHistoryEntivity);
                                    bundle.putInt("type", 0);
                                    startActivity(RedPackageDetailsActivity.class, bundle);
                                }
                            });
                            break;
                        case 2://获取转账
                            bundle.putString("transferId", ToolsUtils.getTransferInfo(content));
                            bundle.putInt("type", 1);
                            startActivityForResult(AffirmReceiveTransferActivity.class, RESULT_TRANSFER_GET, bundle);
                            break;
                        case 3://发送转账
                            bundle.putString("transferId", ToolsUtils.getTransferInfo(content));
                            bundle.putInt("type", 0);
                            startActivity(AffirmReceiveTransferActivity.class, bundle);
                            break;
                        case 4://付款

                            break;
                        case 5://收款

                            break;
                    }
                }
            });
            tbAdapter.setFanYiListener(new ChatRecyclerAdapter.FanYiOnClick() {
                @Override
                public void fanYiOnClick(String content, int type, int isRefresh) {
                    if (0 == isRefresh) {
                        getFanYi(content, type);
                    } else {
                        ImMessage imm = datas.get(type);
                        if (1 == isRefresh) {
                            imm.setIsShowFY("1");
                        } else {
                            imm.setIsShowFY("0");
                        }
                        datas.set(type, imm);
                        tbAdapter.notifyItemChanged(type);
                    }
                }
            });
        } else {
            datas = ImMessage.find(ImMessage.class, "uniqueness=?", myUserId + "__" + uid);
            groupAdapter = new ChatGroupRecyclerAdapter(this, datas, new ChatGroupRecyclerAdapter.onLongClickMsgListenler() {
                @Override
                public void longClick(View view, int position, int type) {

                }
            });
            pullList.setAdapter(groupAdapter);

            groupAdapter.setRedPacketListener(new ChatGroupRecyclerAdapter.RedPacketOnClick() {
                @Override
                public void redOnClick(ImMessage imMessage, int type) {
                    String content = imMessage.getContent();
                    switch (type) {//0-获取；1-发送
                        case 0://
                        case 1:
                            redPackageId = ToolsUtils.getRedPacketInfo(content);
                            getRedPacketHistory(redPackageId);
//                        break;
//                        Bundle bundle = new Bundle();
//                        bundle.putString("redPacketId", ToolsUtils.getRedPacketInfo(content));
//                        startActivity(RedPackageDetailsActivity.class, bundle);
                            break;
                    }
                }
            });

            groupAdapter.setFanYiListener(new ChatGroupRecyclerAdapter.FanYiOnClick() {
                @Override
                public void fanYiOnClick(String content, int type, int isRefresh) {
                    if (0 == isRefresh) {
                        getFanYi(content, type);
                    } else {
                        ImMessage imm = datas.get(type);
                        if (1 == isRefresh) {
                            imm.setIsShowFY("1");
                        } else {
                            imm.setIsShowFY("0");
                        }
                        datas.set(type, imm);
                        groupAdapter.notifyItemChanged(type);
                    }
                }
            });
        }
    }

    private void gotoreddetail(RedPacketHistoryEntivity data, final String uId) {
        if (null != data.getRedPacket() && !"3".equals(data.getRedPacket().getStatus())) {
            if (data.getRedPacket().getRedPacketCount().equals("" + data.getRedPacketHistory().size())) {//已领完
                Bundle bundle = new Bundle();
                bundle.putSerializable("redPacketId", data);
                bundle.putInt("type", 1);
                startActivity(RedPackageDetailsActivity.class, bundle);
            } else {
                if (null == data.getRedPacketHistory() || data.getRedPacketHistory().size() == 0) {//未领取
                    redDialog = MyAlertDialogManages.initShowRedPacket(ChatHistoryActivity.this, data.getRedPacket().getHeadUrl(), data.getRedPacket().getName(), data.getRedPacket().getRedPacketContent(), data.getRedPacket().getRedPacketType(), new MyAlertDialogManages.OnAlertOkImage() {
                        @Override
                        public void onOkImageClick(ImageView mImageView) {
//                            ToolsUtils.startAnimal(mImageView);
                            openRedPacket(uId);
                        }
                    });
                } else {
                    for (int i = 0; i < data.getRedPacketHistory().size(); i++) {
                        if (data.getRedPacketHistory().get(i).getUserId().equals("" + ToolsUtils.getMyUserId())) {//已领取
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("redPacketId", data);
                            bundle.putInt("type", 1);
                            startActivity(RedPackageDetailsActivity.class, bundle);
                            return;
                        }
                    }
                    redDialog = MyAlertDialogManages.initShowRedPacket(ChatHistoryActivity.this, data.getRedPacket().getHeadUrl(), data.getRedPacket().getName(), data.getRedPacket().getRedPacketContent(), data.getRedPacket().getRedPacketType(), new MyAlertDialogManages.OnAlertOkImage() {
                        @Override
                        public void onOkImageClick(ImageView mImageView) {
                            ToolsUtils.startAnimal(mImageView);
                            openRedPacket(uId);
                        }
                    });
                }
            }
        } else {
            showToast(getResources().getString(R.string.red_package_already_overtime));
        }
    }

    /**
     * 获取红包详情
     *
     * @param uId
     */
    public void getRedPacketHistory(final String uId) {
        mPGservice.getRedPacketHistory(uId, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<RedPacketHistoryEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                showToast(ex.getDisplayMessage());
            }

            @Override
            public void onNext(RedPacketHistoryEntivity data) {
                Log.i(TAG, "onNext: ------呵呵----isGroup="+isGroup);
                if (isGroup == 2) {
                    gotoreddetail(data,uId);
                }else {
                    if ("1".equals(data.getRedPacket().getStatus())) {//未领取
                        Log.i(TAG, "onNext: ----002--呵呵----isGroup="+isGroup);
                        redDialog = MyAlertDialogManages.initShowRedPacket(ChatHistoryActivity.this, data.getRedPacket().getHeadUrl(),
                                ToolsUtils.getNick(ToolsUtils.getMyFriendForId(Long.parseLong(uid))), data.getRedPacket().getRedPacketContent(),
                                data.getRedPacket().getRedPacketType(), new MyAlertDialogManages.OnAlertOkImage() {
                                    @Override
                                    public void onOkImageClick(ImageView mImageView) {
//                                    ToolsUtils.startAnimal(mImageView);
                                        openRedPacket(uId);
                                    }
                                });
                    } else if ("2".equals(data.getRedPacket().getStatus())) {//已领取
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("redPacketId", data);
                        bundle.putInt("type", 0);
                        startActivity(RedPackageDetailsActivity.class, bundle);
                    } else {//退回
                        showToast(getString(R.string.red_package_already_overtime));
                    }
                }

            }
        });
    }


    /**
     * 打开红包
     *
     * @param uId
     */
    public void openRedPacket(final String uId) {

        if (!ToolsUtils.currentNetState(this)) {//当前网络不可用
            return;
        }
        mPGservice.openRedPacket(uId, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
                showToast(ex.getDisplayMessage());
                //new ToastUtils().showSingleToast(ex.getDisplayMessage());
            }

            @Override
            public void onNext(String data) {
//                doRainRed();
                if (null != redDialog) redDialog.dismiss();
                mPGservice.getRedPacketHistory(uId, ToolsUtils.getMyUserId()).
                        subscribe(new AbsAPICallback<RedPacketHistoryEntivity>() {
                            @Override
                            protected void onResultError(ApiException ex) {
                                showToast(ex.getDisplayMessage());

                            }

                            @Override
                            public void onNext(RedPacketHistoryEntivity data) {
                                if (data != null) {
//                                    doCancelRain();
                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable("redPacketId", data);
                                    bundle.putInt("type", 0);
                                    startActivity(RedPackageDetailsActivity.class, bundle);
                                }
                            }
                        });
                //  handler.sendEmptyMessageDelayed(99, 3000);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.pre_v_back:
                finish();
                break;
        }
    }



    /**
     * 翻译
     */
    //	appid+q+salt+密钥 的MD5值
    private String getMd5Text(String q) {
        String dengStr = "20161219000034254" + q + ToolsUtils.getMyUserId() + "JAFNz90QW9JJzeXp3sNj";
        return MD5.MD532(dengStr);
    }

    private void getFanYi(String str, final int type) {
        if (!ToolsUtils.currentNetState(this)) {//当前网络不可用
            return;
        }
        Log.i(TAG, "getFanYi: getLanguage=" + Locale.getDefault().getCountry());
//        Log.i(TAG, "getFanYi: getMyUserId="+ToolsUtils.getMyUserId());

        String biao = Locale.getDefault().getLanguage();
        if (biao.equals("zh")) {
            biao = biao + Locale.getDefault().getCountry();
        }

        mPGservice.getTextFanYi(str, "auto", ToolsUtils.getMyFanYiMap().get(biao), "20161219000034254", ToolsUtils.getMyUserId(), getMd5Text(str)).subscribe(new AbsAPICallback<FanYiBean>() {
            @Override
            protected void onResultError(ApiException ex) {
                new ToastUtils().showSingleToast(getString(R.string.commit_translante_defeat));
            }

            @Override
            public void onNext(FanYiBean data) {
                Log.i(TAG, "onNext: fanyi=" + data);
                ImMessage imm = datas.get(type);
                imm.setContent_fy(new Gson().toJson(data));
                imm.setIsShowFY("1");
                datas.set(type, imm);
                if (isGroup == 1) {
                    tbAdapter.notifyDataSetChanged();
                } else {
                    groupAdapter.notifyDataSetChanged();
                }
            }
        });
    }
}
